package com.fingard.dsp.bank.directbank.vbao01;

import java.net.URLDecoder;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISMSRec;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.dsp.bank.reqrespobj.smsrec.ReqSMSRec;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.CombinedAuthenticationRequest;
import com.vbao.service.trade.bean.request.CombinedDKRequest;
import com.vbao.service.trade.bean.request.SingleQueryRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.TradeCodeEnum;

/**
 * 微保快捷支付
 * 
 * 应用场景：
 * 	   此种形式的组合支付分两步， 
 *   1、商户先请求平台进行鉴权，鉴权成功后支付，支付平台或商户给用户发送短信验证码，
 * 	 2、商户上传短信验证码,再请求支付平台进行代扣
 *
 */
public class VBAO01SMSRec extends VBAO01Base implements ISMSRec {
	/**
	 * 鉴权+获取验证码+提交验证码
	 * 
	 * step01:鉴权、获取验证码
	 * step02:提交验证码支付
	 */
	@Override
	public RetAtsSingle d_9110_SMSRec(ReqSMSRec p_req9110) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9110.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();	
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9110.singleDetail.recAct, "");
			if(actItem != null) {
				//第一步，鉴权获取短信验证码
				if(p_req9110.singleDetail.step.equals("01")) {
					CombinedAuthenticationRequest authRequest = new CombinedAuthenticationRequest();
					
					authRequest.setVersion("6.0"); /* 版本号 */
					
					authRequest.setInputCharset("UTF-8"); /* 字符集(固定为UTF-8) */
					
					authRequest.setSignType("MD5"); /* 加密方式(固定为MD5) */
					
					authRequest.setCustomerNo(actItem.merchantId); /* 商户号 */
					
					authRequest.setGoodNo(getBankConfig().getValueAsString("GoodNo")); /* 商户商品代号 */
					
					authRequest.setOrderNo(p_req9110.singleDetail.askNumber); /* 商户订单号 */
					
					authRequest.setBankCode(getBankConfig().getMapValueByKey("BankCodeMapping", p_req9110.singleDetail.payBankCode)); /* 银行编码(ICBC等字符编码) */
					
					if ("3".equals(p_req9110.singleDetail.cardType) || "4".equals(p_req9110.singleDetail.cardType)) {
						authRequest.setBankCardType("2"); // 信用卡
					} else if ("1".equals(p_req9110.singleDetail.cardType)) {
						authRequest.setBankCardType("1"); // 存折
					} else {
						authRequest.setBankCardType("0");// 银行卡(默认)
					}
					
					authRequest.setBankCardNo(p_req9110.singleDetail.payAct); /* 卡号 */
					
					authRequest.setBankCardName(p_req9110.singleDetail.payName); /* 开户姓名 */
					
					authRequest.setCertType(convertCertTypeToBank(p_req9110.singleDetail.certType)); /* 证件类型 */
					
					authRequest.setCertId(p_req9110.singleDetail.certNum); /* 证件号 */
					
					authRequest.setMobile(p_req9110.singleDetail.cellPhone); /* 手机号 */
					
					if(p_req9110.singleDetail.cvv2.length() > 0 && p_req9110.singleDetail.expiredDate.length() > 0){
						authRequest.setCreditValid(p_req9110.singleDetail.expiredDate); /* 信用卡有效期(格式：YYMM) */
						authRequest.setCreditCvv2(p_req9110.singleDetail.cvv2); /* 信用卡CVV2 */
				    }
					
					authRequest.setSmsUrl(actItem.returnURL); /* 发送短信验证码地址 */
					
					authRequest.setSmsText(""); /* 短信内容 */
					
					authRequest.setBranch1(""); /* 商户下属一级分支机构 */
					
					authRequest.setBranch2(""); /* 商户下属一级分支机构 */
					
					authRequest.setBranch3(""); /* 商户下属一级分支机构 */
					
					authRequest.setSalesChannel(""); /* 商户销售渠道 */
					
					authRequest.setCustProductCode(""); /* 商户产品代码 */

					//组装发送报文
					VbaoChargeSystemHandler vbaoHandler = new VbaoChargeSystemHandler();
				 	TradeRequestXml tradeRequestXml = vbaoHandler.creatRequestXml(authRequest,actItem.saltKey,getCharset(),TradeCodeEnum.COMBINED_AUTHENTICATION.getCode());
					
				 	WriteBankLogLn2("微保快捷支付鉴权获取验证码加密前报文明文:\r\n" + tradeRequestXml.getOriRequestXml());
				 	WriteBankLogLn2("微保快捷支付鉴权获取验证码请求数据:\r\n" + tradeRequestXml.getRequestXml());
				 	
			 		if(tradeRequestXml.getErrMsg() == null)	{
			 			String submitUrl = bankFront.getUrl("911001");
			 			if (StringHelper.isNullOrEmpty(submitUrl)) {
			 				tmpRetDetail.respCode = "-1";
							tmpRetDetail.respInfo = "[微保快捷支付鉴权获取验证码服务地址:911001]内容为空,请检查BankFront.xml相关配置!";
							
							return retAts;
			 			}
			 			
					 	WriteBankLogLn2("微保快捷支付鉴权获取验证码服务地址:" + submitUrl);
					 	
			 			// 发送微保并获取返回
			  			String tmpSmsRecRespXml = vbaoHandler.http(submitUrl, tradeRequestXml.getRequestXml(), getCharset());
			  			WriteBankLogLn2("微保快捷支付鉴权获取验证码响应数据:\r\n" + tmpSmsRecRespXml);
			  			
			  			if (StringHelper.hasAnyChar(tmpSmsRecRespXml)) {
			  				 // 进行解密
							String tmpSmsRecOriXml = Base64vbao.decode(tmpSmsRecRespXml, getCharset());
							//tmpSmsRecOriXml = new String(tmpSmsRecOriXml.getBytes(), getCharset());
							WriteBankLogLn2("微保快捷支付鉴权获取验证码解密后明文:\r\n" + tmpSmsRecOriXml);
				  			
							// 执行验签
							boolean flag = vbaoHandler.verifySignature(tmpSmsRecOriXml, actItem.saltKey, getCharset());
							if (flag) {
								String tmpStrRet = URLDecoder.decode(tmpSmsRecOriXml, getCharset());
								
								StringBuilder tmpSbMsg = new StringBuilder();
								XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
								
								if (tmpBkReader != null) {
									tmpRetDetail.respCode = "0";
									tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
									
									String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
									if (tmpReturnCode.equals("T")) {
										String resultCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
										if ("00000".equals(resultCode)) {
											tmpRetDetail.respInfo = "已提交";
					        				tmpRetDetail.transState = PaymentState.SUCCESS;
					        				tmpRetDetail.token = tmpBkReader.getFirstText("/TResponse/ValidationInfo/TraceNum");
										} else {
											tmpRetDetail.transState = tmpReturnCode + "+" + resultCode;
											tmpRetDetail.payInfoCode = resultCode;
										}
									} else {
										tmpRetDetail.transState = PaymentState.FAIL;
										tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
									}
								} else {
									tmpRetDetail.respCode = "-1";
									tmpRetDetail.respInfo = tmpSbMsg.toString();
								}
							} else {
								tmpRetDetail.respCode = "-1";
				  				tmpRetDetail.respInfo = "微保快捷支付鉴权获取验证码本地验签失败!";
							}
			  			} else {
			  				tmpRetDetail.respCode = "-1";
			  				tmpRetDetail.respInfo = "微保快捷支付鉴权获取验证码响应内容为空,请联系微保相关技术人员!";
						}
			 		} else {
			 			tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = tradeRequestXml.getErrMsg();
			 		}
					
				// 第二步 发送短信支付
				} else if (p_req9110.singleDetail.step.equals("02")) {
					CombinedDKRequest combinedDKRequest = new CombinedDKRequest();
					
					combinedDKRequest.setVersion("6.0"); /* 版本号 */
					
					combinedDKRequest.setInputCharset("UTF-8"); /* 字符集(固定为UTF-8) */
					
					combinedDKRequest.setSignType("MD5"); /* 加密方式(固定为MD5) */
					
					combinedDKRequest.setCustomerNo(actItem.merchantId); /* 商户号 */
					
					combinedDKRequest.setGoodNo(getBankConfig().getValueAsString("GoodNo")); /* 商户商品代号 */
					
					combinedDKRequest.setOrderNo(p_req9110.singleDetail.askNumber); /* 商户订单号 */
					
					combinedDKRequest.setOrderAmount(p_req9110.singleDetail.payAmount); /* 商户订单金额(单位:元) */
					
					combinedDKRequest.setBankCode(getBankConfig().getMapValueByKey("BankCodeMapping", p_req9110.singleDetail.payBankCode));/* 银行编码 */
					
					// 0 银行卡，1 存折，2 信用卡
					if ("3".equals(p_req9110.singleDetail.cardType) || "4".equals(p_req9110.singleDetail.cardType)) {
						combinedDKRequest.setBankCardType("2");
					} else if ("1".equals(p_req9110.singleDetail.cardType)) {
						combinedDKRequest.setBankCardType("1");
					} else {
						combinedDKRequest.setBankCardType("0");// 银行卡
					}
					
					combinedDKRequest.setBankCardNo(p_req9110.singleDetail.payAct); /* 卡号 */
					
					combinedDKRequest.setBankCardName(p_req9110.singleDetail.payName); /* 开户姓名 */
					
					combinedDKRequest.setBankProvince(""); /* 付款账户归属省份编码 */
					
					combinedDKRequest.setBankCity(""); /* 付款账户归属城市编码 */
					
					combinedDKRequest.setBankLineCode(""); /* 付款账户联行号 */
					
					combinedDKRequest.setBankName(""); /* 付款账户开户行名称 */
					
					combinedDKRequest.setProtocolNo(p_req9110.singleDetail.authCode); /* 扣款协议号 */
					
					combinedDKRequest.setCertType(convertCertTypeToBank(p_req9110.singleDetail.certType)); /* 证件类型  信用卡代扣必填 */
					combinedDKRequest.setCertId(p_req9110.singleDetail.certNum); /* 证件号 信用卡代扣必填 */
					combinedDKRequest.setMobile(p_req9110.singleDetail.cellPhone); /* 手机号 */
					
					if(p_req9110.singleDetail.cvv2.length() > 0 && p_req9110.singleDetail.expiredDate.length() > 0){
						combinedDKRequest.setCreditValid(p_req9110.singleDetail.expiredDate); /* 信用卡有效期: YYMM */
						combinedDKRequest.setCreditCvv2(p_req9110.singleDetail.cvv2); /* 信用卡CVV2 */
				    }
					
					String productName = p_req9110.singleDetail.memo;
					if (StringHelper.isNullOrEmpty(productName)) {
						productName = p_req9110.singleDetail.useType;
					} 
					if (StringHelper.isNullOrEmpty(productName)) {
						productName = p_req9110.singleDetail.description;
					} 
					if (StringHelper.isNullOrEmpty(productName)) {
						productName = p_req9110.singleDetail.abstractATS;
					} 
					
					combinedDKRequest.setProductName(productName);/* 商品名称(保单号) ，在银行允许下为银行摘要 */
					
					combinedDKRequest.setProductDesc(p_req9110.singleDetail.description); /* 商品描述信息 */
					
					combinedDKRequest.setNotifyUrl(actItem.notifyURL); /* 服务器通知地址 */
					
					combinedDKRequest.setCodeNo(p_req9110.singleDetail.verifyCode); /* 鉴权验证码 */
					
					combinedDKRequest.setTraceNum(p_req9110.singleDetail.token); /* 鉴权交易号 */
					
					combinedDKRequest.setExt1(""); /* 备注一 */
					
					combinedDKRequest.setExt2(""); /* 备注二 */
					
					//组装发送报文
					VbaoChargeSystemHandler vbaoHandler = new VbaoChargeSystemHandler();
				 	TradeRequestXml tradeRequestXml = vbaoHandler.creatRequestXml(combinedDKRequest, actItem.saltKey , getCharset() ,TradeCodeEnum.COMBINED_DK.getCode());
					
				 	WriteBankLogLn2("微保快捷支付发送验证码加密前明文:\r\n" + tradeRequestXml.getOriRequestXml());
					WriteBankLogLn2("微保快捷支付发送验证码请求数据:\r\n" + tradeRequestXml.getRequestXml());
				 	
			 		if(tradeRequestXml.getErrMsg() == null)	{
			 			String submitUrl = bankFront.getUrl("911002");
			 			if (StringHelper.isNullOrEmpty(submitUrl)) {
							tmpRetDetail.respCode = "-1";
							tmpRetDetail.respInfo = "[微保快捷支付发送验证码地址:911002]内容为空,请检查BankFront.xml相关配置!";
							
							return retAts;
						}
			 			
					 	WriteBankLogLn2("微保快捷支付发送验证码服务地址:" + submitUrl);
					 	
			 			//获取返回报文
			  			String tmpSmsRecRespxml = vbaoHandler.http(submitUrl, tradeRequestXml.getRequestXml(), getCharset());
			  			WriteBankLogLn2("微保快捷支付发送验证码响应数据:\r\n" + tmpSmsRecRespxml);
			  			
			  			if (StringHelper.hasAnyChar(tmpSmsRecRespxml)) {
							// 进行解密
							String tmpSmsRecOriXml = Base64vbao.decode(tmpSmsRecRespxml, getCharset());
							//tmpSmsRecOriXml = new String(tmpSmsRecOriXml.getBytes(), getCharset());
							WriteBankLogLn2("微保快捷支付发送验证码解密后明文:\r\n" + tmpSmsRecOriXml);
							
							// 执行验签
							boolean flag = vbaoHandler.verifySignature(tmpSmsRecOriXml, actItem.saltKey, getCharset());
							if (flag) {
								String tmpStrRet = URLDecoder.decode(tmpSmsRecOriXml, getCharset());
								
								StringBuilder tmpSbMsg = new StringBuilder();
								XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
								
								if (tmpBkReader != null) {
									tmpRetDetail.respCode = "0";
									tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
									
									String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
									String errorCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
									if (tmpReturnCode.equals("T")) {
										tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");
										tmpRetDetail.transAmt = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderAmount");
										tmpRetDetail.transState = tmpReturnCode + "+" + errorCode + "+" + tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus");
										tmpRetDetail.payInfoCode = errorCode;
									} else {
										tmpRetDetail.transState = tmpReturnCode + "+" + errorCode;
										tmpRetDetail.payInfoCode = errorCode;
									}
								} else {
									tmpRetDetail.respCode = "-1";
									tmpRetDetail.respInfo = tmpSbMsg.toString();
								}
							} else {
								tmpRetDetail.respCode = "-1";
								tmpRetDetail.respInfo = "微保快捷支付发送验证码本地验签失败!";
							}
			  			} else {
			  				tmpRetDetail.respCode = "-1";
			  				tmpRetDetail.respInfo = "微保快捷支付发送验证码返回内容为空,请联系微保相关技术人员!";
			  			}
			 		} else {
			 			tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = tradeRequestXml.getErrMsg();
			 		}
				} else {
					tmpRetDetail.respCode = "0";
					tmpRetDetail.respInfo = "未能识别的step：" + p_req9110.singleDetail.step;
					tmpRetDetail.reqSeqID = p_req9110.singleDetail.askNumber;
					tmpRetDetail.transState = PaymentState.FAIL_Payment;
					tmpRetDetail.payInfoCode = "E9981";
				}
			} else {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = "未找到账号:[" + p_req9110.singleDetail.recAct + "]商户配置信息";
				tmpRetDetail.reqSeqID = p_req9110.singleDetail.askNumber;
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = FailCode.E9981;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		if ("-1".equals(tmpRetDetail.respCode)) {
			tmpRetDetail.reqSeqID = p_req9110.singleDetail.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingle d_9146_QrySMSRec(ReqQrySingle p_req9146) throws Exception{
		RetAtsSingle retAts = new RetAtsSingle(p_req9146.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		try{
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9146.recAct, "");
			if(actItem != null){
				SingleQueryRequest singleQueryRequest = new SingleQueryRequest();
				
				singleQueryRequest.setVersion("6.0"); /* 版本号 */
				
				singleQueryRequest.setInputCharset("UTF-8"); /* 字符集(固定为UTF-8) */
				
				singleQueryRequest.setSignType("MD5"); /* 加密方式(固定为MD5) */
				
				singleQueryRequest.setCustomerNo(actItem.merchantId); /* 商户号 */
				
				singleQueryRequest.setPayDate(Format.Date8Format.format(p_req9146.getBgnDateTime())); /* 支付日期(格式：YYYYMMDD) */
				
				singleQueryRequest.setOrderNo(p_req9146.askNumber); /* 商户订单号 */
				
				singleQueryRequest.setSerialNo(""); /* 微保支付流水号 */

				// 组装发送报文
				VbaoChargeSystemHandler vbaoHandler = new VbaoChargeSystemHandler();
				TradeRequestXml tradeRequestXml = vbaoHandler.creatRequestXml(singleQueryRequest, actItem.saltKey, getCharset(), TradeCodeEnum.SINGLE_QUERY.getCode());
				
				WriteBankLogLn2("微保快捷支付状态查询加密前明文:\r\n" + tradeRequestXml.getOriRequestXml());
				WriteBankLogLn2("微保快捷支付状态查询发送报文密文:\r\n" + tradeRequestXml.getRequestXml());
				
				if (tradeRequestXml.getErrMsg() == null) {
					String submitUrl = bankFront.getUrl("9146");
					if (StringHelper.isNullOrEmpty(submitUrl)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "[微保快捷支付状态查询地址:9146]内容为空,请检查BankFront.xml相关配置!";
						
						return retAts;
					}
					
					WriteBankLogLn2("快捷支付状态查询服务地址:" + submitUrl);
					
					// 获取返回报文
					String tmpSmsRecQueryRespXml = vbaoHandler.http(submitUrl, tradeRequestXml.getRequestXml(), getCharset());
					WriteBankLogLn2("快捷支付状态查询响应数据密文:\r\n" + tmpSmsRecQueryRespXml);
					
					if (StringHelper.hasAnyChar(tmpSmsRecQueryRespXml)) {
						// 进行解密
						String tmpSmsRecQueryOriXml = Base64vbao.decode(tmpSmsRecQueryRespXml, getCharset());
						//tmpSmsRecQueryOriXml = new String(tmpSmsRecQueryOriXml.getBytes(), getCharset());
						WriteBankLogLn2("微保快捷支付状态查询解密后明文:\r\n" + tmpSmsRecQueryOriXml);
						
						// 执行验签
						boolean flag = vbaoHandler.verifySignature(tmpSmsRecQueryOriXml, actItem.saltKey, getCharset());
						if (flag) {
							String tmpStrRet = URLDecoder.decode(tmpSmsRecQueryOriXml, getCharset());
							
							StringBuilder tmpSbMsg = new StringBuilder();
					        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
			
						    if (tmpBkReader != null) {
						    	tmpRetDetail.respCode = "0";
						    	tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
						    	tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");
							    
							    String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
							    if (tmpReturnCode.equals("T")) {
							    	tmpRetDetail.transAmt = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderAmount");
							    	tmpRetDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode") + "+" + tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus");
							    	tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
								} else {
									tmpRetDetail.transState = tmpReturnCode + "+" + tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
									tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
								}
						    } else {
						    	tmpRetDetail.respCode = "-1";
						    	tmpRetDetail.respInfo = tmpSbMsg.toString();
						    }
						} else {
							tmpRetDetail.respCode = "-1";
							tmpRetDetail.respInfo = "微保快捷支付状态查询本地验签失败!";
						}
					} else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "微保快捷支付状态查询返回内容为空,请联系微保相关技术人员!";
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tradeRequestXml.getErrMsg();
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "未找到账号:[" + p_req9146.recAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		if ("-1".equals(tmpRetDetail.respCode)) {
			tmpRetDetail.reqSeqID = p_req9146.askNumber;
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
